package com.manager.common.ssh;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.apache.commons.lang3.StringUtils;

import java.util.Properties;

public class SftpClient {

    private  String ip;

    private  String userName;

    private  String password;

    private  int port;

    private  Session sshSession;

    private  Channel channel;

    private  ChannelSftp sftp;

    public SftpClient(String ip, String userName, String password, int port) {
        this.ip = ip;
        this.userName = userName;
        this.password = password;
        this.port = port;
    }

    public  ChannelSftp getChannelSftp() throws Exception{
        JSch jsch = new JSch();

        sshSession = jsch.getSession(userName, ip, port);

        if (!StringUtils.isEmpty(password)) {
            sshSession.setPassword(password);
        }

        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");

        sshSession.setConfig(sshConfig);

        sshSession.connect();

        channel = sshSession.openChannel("sftp");
        channel.connect();

        sftp = (ChannelSftp) channel;

        return sftp;
    }

    public void close(){
        if(channel != null){
            channel.disconnect();
        }
        if(sshSession != null){
            sshSession.disconnect();
        }
        if(sftp != null){
            sftp.disconnect();
        }
    }
}
